//
//  CLSlidersViewController.m
//  chanlin
//
//  Created by Ryan on 14-11-10.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLSlidersViewController.h"
#import "CLGloble.h"
#import "IfengPhotoLabel.h"
#import "CustomCoretextLabel.h"
#import "CLPhotoViewController.h"
#import "Sgr_macro.h"
#import "CLDocModel.h"
#import "NSObject+sagittarius.h"
#import "IFToolBarViewController.h"
#import "CLComentDataModel.h"
#import "CTCommentViewController.h"
#import "CLPushAnimatedRight.h"
#import "CLSystemPushAnimated.h"
#import "CLGlobleDataModel.h"
#import "SgrGCD.h"
#import "UIView+Utils.h"

#define bottomViewdefaultHeight 90.0
@interface CLSlidersViewController ()

@property (nonatomic,strong) AQRSlidesView *slides;
@property (nonatomic,strong) UIView *bottomView;
@property (nonatomic, strong) UIImageView *photoBottomView;
@property (nonatomic,strong) UIImageView *lineImageView;
@property (nonatomic,strong) IfengPhotoLabel *p_titleLabel;
@property (nonatomic,strong) CustomCoretextLabel *percentLabel; // 当前页指示Label
@property (nonatomic,strong) UIImageView *rightLogoImg;
@property (nonatomic,strong) UIScrollView *infoScrollView; //幻灯介绍滚动View
@property (nonatomic,strong) IfengPhotoLabel *p_infoLabel;
@property (nonatomic,strong) CustomCoretextLabel *indexLabel;
@property (nonatomic,strong) UIButton *h_backButton;
@property (nonatomic,strong) UIButton *h_download;
@property (nonatomic, assign) NSInteger i_index;
@property (nonatomic, assign) CGFloat temp_bottomHeight;
@property (nonatomic,unsafe_unretained) BOOL isHidden;
@property (nonatomic, assign) UIInterfaceOrientation photointerfaceOrientation;
//@property (nonatomic,strong) UIView *navagationView;
@property (nonatomic,strong) NSString *shareUrl;
@property (nonatomic,strong) NSString *sharepicUrl;
@property (nonatomic,strong) NSArray *dataArray;
@property (nonatomic, assign) NSInteger i_group;                //记录当前group
@property (nonatomic,strong) UIView *reTry;
@property (nonatomic, strong) NSString *str_title;              //旋转时记录title
@property (nonatomic, strong) NSString *str_percent;            //记录当前页数
@property (nonatomic, strong) NSString *str_info;               //记录当前info
@property (nonatomic, assign) BOOL finishMove;
@property (nonatomic, assign) CGFloat f_initial;                //记录底部视图初始位置
@property (nonatomic,strong)UIView *gapView;


@property (nonatomic,strong)UIButton *commentButton;

@property (nonatomic,strong)NSDictionary *commentDic;

@property (nonatomic,strong) NSArray *relations_;

@property (nonatomic,strong) NSDictionary *next_;

@property (nonatomic,unsafe_unretained)BOOL willBack;

@end

@implementation CLSlidersViewController

- (void)viewDidLoad {
   
    [super viewDidLoad];
     _finishMove = YES;
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.modalPresentationCapturesStatusBarAppearance = NO;
    
    self.view.backgroundColor=[UIColor whiteColor];
    
    self.view=[[UIView alloc] initWithFrame:
               CGRectMake(0, 0, GlobleWidth, GlobleHeight)];
    self.view.autoresizesSubviews = YES;
    
    self.slides = [[AQRSlidesView alloc] initWithFrame:CGRectMake(0, 0, GlobleWidth, GlobleHeight)];
    self.slides.datasource = self;
    [self.view addSubview:self.slides];
    

    
    
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, GlobleHeight-bottomViewdefaultHeight-BOTTOMGAP-44.0f, GlobleWidth, bottomViewdefaultHeight)];
    self.bottomView.backgroundColor = [UIColor clearColor];
    self.bottomView.userInteractionEnabled = YES;
    self.bottomView.clipsToBounds = YES;
    //self.bottomView.backgroundColor=[UIColor redColor];
    
    _photoBottomView = [[UIImageView alloc] initWithFrame:CGRectMake(0, GlobleHeight-200.0/2-44.0f, GlobleWidth, 200.0/2)];
    _photoBottomView.userInteractionEnabled = YES;
    [_photoBottomView setImage:[UIImage imageNamed:@"photo_bottom_vertical.png"]];
    [self.view addSubview:_photoBottomView];
 
    
    UIPanGestureRecognizer *bottomPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didPanBottomView:)];
    bottomPanGesture.delegate = self;
    [self.bottomView addGestureRecognizer:bottomPanGesture];
    
    UISwipeGestureRecognizer *swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] init];
    [swipeGestureRecognizer addTarget:self action:@selector(didSwipeBottomView:)];
    [swipeGestureRecognizer setNumberOfTouchesRequired:1];
    [swipeGestureRecognizer setDirection:UISwipeGestureRecognizerDirectionDown];
    [self.bottomView addGestureRecognizer:swipeGestureRecognizer];
    [bottomPanGesture requireGestureRecognizerToFail:swipeGestureRecognizer];
    
    _lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(220.0+36.0f, 0, 1, (self.bottomView.frame.size.height>bottomViewdefaultHeight)?self.bottomView.frame.size.height:bottomViewdefaultHeight)];
    _lineImageView.alpha = 0.5;
    [_lineImageView setImage:[UIImage imageNamed:@"photo_line.png"]];
    [self.bottomView addSubview:_lineImageView];
    
    self.p_titleLabel = [[IfengPhotoLabel alloc] init];
    self.p_titleLabel.backgroundColor = [UIColor clearColor];
    self.p_titleLabel.userInteractionEnabled = YES;
    self.p_titleLabel.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    [self.p_titleLabel setFrame:CGRectMake(0, 0, 220.0, 1000.0)];
    
    //右侧logo
    self.rightLogoImg = [[UIImageView alloc]init];
    self.rightLogoImg.frame = CGRectMake(_lineImageView.right+13, _lineImageView.top, 21, 44);
    [self.rightLogoImg setImage:[UIImage imageNamed:@"slider_logo Img.png"]];
    [self.bottomView addSubview:self.rightLogoImg];
    
    // 当前图下标指示Label
    self.percentLabel = [[CustomCoretextLabel alloc] init];
    _percentLabel.font = [UIFont systemFontOfSize:8.5f];
    _percentLabel.textColor = [UIColor whiteColor];
    _percentLabel.backgroundColor = [UIColor clearColor];
    //  _percentLabel.textAlignment = UITextAlignmentRight;
    _percentLabel.text = @"1/1";
    [self.bottomView addSubview:_percentLabel];
    
    [self.bottomView addSubview:self.p_titleLabel];
    
    // 幻灯介绍
    // --滚动view
    self.infoScrollView = [[UIScrollView alloc] init];
    self.infoScrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    [self.bottomView addSubview:_infoScrollView];

    // --内容label
    self.p_infoLabel = [[IfengPhotoLabel alloc] initWithFrame:CGRectZero];
    self.p_infoLabel.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    self.p_infoLabel.backgroundColor = [UIColor clearColor];
    [self.p_infoLabel setFrame:CGRectMake(0, 0, 220.0, 1000.0)];
    [self.infoScrollView addSubview:self.p_infoLabel];
    
    [self.view addSubview:self.bottomView];
    
    // 隐藏掉导航栏，全屏查看的时候用到 -- HouJia ---------
    self.indexLabel=[[CustomCoretextLabel alloc] initWithFrame:CGRectZero];
    self.indexLabel.backgroundColor=[UIColor clearColor];
    self.indexLabel.textAlignment = NSTextAlignmentCenter;
    self.indexLabel.font = [UIFont systemFontOfSize:8.5f];
    self.indexLabel.frame=CGRectZero;
    self.indexLabel.hidden=YES;
    [self.view addSubview:self.indexLabel];
    // ----------------------------------------------
    self.view.backgroundColor=[UIColor blackColor];
    
    _h_backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_h_backButton setBackgroundColor:[UIColor clearColor]];
    
    [_h_backButton setFrame:CGRectMake(0, GlobleHeight-50.f, 50.f, 50.f)];
    _h_backButton.contentEdgeInsets=UIEdgeInsetsMake(10.f, 10.f, 10.f, 10.f);
    [_h_backButton setImage:[UIImage imageNamed:@"nav_back_photo_horizonal.png"] forState:UIControlStateNormal];
    [_h_backButton addTarget:self action:@selector(backFromPhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_h_backButton];
    
    
    _h_download = [UIButton buttonWithType:UIButtonTypeCustom];
    _h_download.alpha = 1;
    _h_download.contentEdgeInsets=UIEdgeInsetsMake(13.f, 13.f, 13.f, 13.f);
    [_h_download setImage:[UIImage imageNamed:@"slider_font.png"] forState:UIControlStateNormal];
    [_h_download addTarget:self action:@selector(downLoadBtPressed:) forControlEvents:UIControlEventTouchUpInside];
    if(!self.isCover)
    [self.view addSubview:_h_download];
    
    [self navigatorView];
    
    _h_backButton.hidden = YES;
    _h_download.hidden = YES;
    __weak typeof(self) me=self;
    
    if(self.isCover){
        [[CLDocModel sharedInstance] getCoverUiBlock:^(BOOL success, id responseObj, NSString *message) {
            me.dataArray=[[responseObj sgrGetDictionaryForKey:@"data"] sgrGetArrayForKey:@"morepic"];
            me.str_title=[[responseObj sgrGetDictionaryForKey:@"data"] sgrGetStringForKey:@"title"];
            me.i_group=[me.dataArray count];
            [me.slides reloadData];

        }];
    }else{
    
    [[CLDocModel sharedInstance] getSlider:self.itemId
                                   uiBlock:^(BOOL success, id responseObj, NSString *message) {
                                       //NSLog(@"%@",responseObj);
                                       me.shareUrl=[[responseObj sgrGetDictionaryForKey:@"data"] sgrGetStringForKey:@"shareurl"];
                                       NSArray *pics=[[responseObj sgrGetDictionaryForKey:@"data"] sgrGetArrayForKey:@"morepic"];
                                       me.sharepicUrl = [[responseObj sgrGetDictionaryForKey:@"data"] sgrGetStringForKey:@"sharepic"];
                                       NSMutableArray *array=[NSMutableArray arrayWithArray:pics];
                                       
                                       NSArray *relations=[[responseObj sgrGetDictionaryForKey:@"data"] sgrGetArrayForKey:@"relation"];
                                       if(relations){
                                           [array addObject:@{@"image":@"",
                                                              @"description":@"",
                                                              @"type":@"behind",
                                                              @"relations":relations}];
                                           me.relations_=relations;
                                       }
                                       
                                NSDictionary *next=[[responseObj sgrGetDictionaryForKey:@"data"] sgrGetDictionaryForKey:@"next"];
                                       if(next){
                                           me.next_=next;
                                       }
                                       
                                       me.dataArray=array;
                                       me.str_title=[[responseObj sgrGetDictionaryForKey:@"data"] sgrGetStringForKey:@"title"];
                                       me.i_group=[me.dataArray count];
                                       [me.slides reloadData];
                                       [me requestComment];
                                       
                                       
                                       [MobClick event:@"page"
                                            attributes:@{@"pageId":[@"slide_" stringByAppendingString:_safeStr(me.itemId)],
                                                         @"title":_safeStr(me.str_title)}];
                                   
     
    }];
    }
    [self.view setNeedsLayout];
}

- (void)hiddenInfo:(BOOL)isHidden{
    if(isHidden){
        self.indexLabel.alpha=0.f;
        self.bottomView.alpha=0.f;
    }else{
        self.indexLabel.alpha=1.f;
        self.bottomView.alpha=1.f;
    }
}

- (void)backFromPhoto{
    self.willBack=YES;
    if(self.dispatchObj==[CLSystemPushAnimated sharedInstance]){
        [self.dispatchObj pop];
    }else{
        [UIView animateWithDuration:0.35 animations:^{
            [[CLGloble sharedInstance] didChangeToInterfaceOrientationPortrait];
            [UIViewController attemptRotationToDeviceOrientation];
        } completion:^(BOOL finished) {
            [self.dispatchObj pop];
        }];
    }
    
   
}

- (void)requestComment{
    __weak typeof(self) me=self;
    [[CLComentDataModel sharedInstance] loadTopicWithUrl:nil
                                                   title:me.str_title
                                                     doc:self.itemId
                                                   block:^(BOOL success, NSDictionary *dic) {
                                                       if(success){
                                                           me.commentDic=dic;
                                                     
                                                           [me.tool update:[dic sgrGetIntForKey:@"count"]];
                                                          
                                                       }else{
                                                           
                                                       }
                                                       // NSLog(@"%@",dic);
                                                       
                                                   }];
}


- (CLBehindeView *)getCLBehindeView{
    if(!self.behindView){
        self.behindView=[[CLBehindeView alloc] init];
        self.behindView.frame=self.view.bounds;
        [self.behindView loadArray:self.relations_];
        [self.behindView loadNextDic:self.next_];
    }
//    self.tool.view.hidden=YES;
//    [self k_currentController].tool.view.hidden = YES;
    return self.behindView;
}

- (void)changeHidden{
    
//    if (_isBehindView || (self.reTry.hidden==NO)) {
//        return;
//    }
    
    if(self.isHidden){
        [self updateBottomViewToInterfaceOrientation:_photointerfaceOrientation];
        self.bottomView.hidden=NO;
        self.tool.view.hidden=NO;
        self.indexLabel.hidden=YES;
        _photoBottomView.hidden=NO;
        self.isHidden=NO;
    }else{
        self.slides.alpha = 1;
        self.bottomView.hidden=YES;
        self.self.tool.view.hidden=YES;
        self.indexLabel.hidden=NO;
        _photoBottomView.hidden=YES;
        self.isHidden=YES;
    }
}

- (Class)childrenClass{
    return [CLPhotoViewController class];
}

- (int)photoCount{
    return self.dataArray?(int)[self.dataArray count]:0;
  
}

- (NSArray *)slidesData{
    return self.dataArray;
}

- (UIInterfaceOrientation)sliderInterfaceOrientation
{
    return _photointerfaceOrientation;
}

- (NSObject *)childrenCreateParams{
    return self;
}

- (int)initIndex
{
    return [self.slides scrollIndex];
}

- (void)setTitle:(NSDictionary *)dic {
    
    
    
    
    
        //        _h_backButton.hidden = NO;
        //        _h_download.hidden = NO;
        if (self.indexLabel.hidden) {
            self.bottomView.hidden = NO;
            self.tool.view.hidden = NO;
            _photoBottomView.hidden = NO;
        }
        else {
            self.bottomView.hidden = YES;
            self.tool.view.hidden = YES;
            _photoBottomView.hidden = YES;
        }
    
    
    
    
    //检测当前图集有无后贴片
    
    int index=[self.slides scrollIndex]+1;
   
    
    NSString *percentStr = [NSString stringWithFormat:@"%d/%ld",index,(long)_i_group];
 
    
    
    _str_percent = percentStr;
    _i_index = index;
   
    
    NSString *info=[dic sgrGetStringForKey:@"description"];
    _str_info = info;
    
    [self updateTitleLabelToInterfaceOrientation:_photointerfaceOrientation];
    [self updatePercentLabelToInterfaceOrientation:_photointerfaceOrientation];
    [self updateInfoLabelToInterfaceOrientation:_photointerfaceOrientation];
    [self updateBottomViewToInterfaceOrientation:_photointerfaceOrientation];
    [self updateButtonsToInterfaceOrientation:_photointerfaceOrientation];
    
    self.infoScrollView.contentSize = CGSizeMake(0, 0);
    [self.infoScrollView flashScrollIndicators];
   
    [self changePageIndex];
}


-(void)changePageIndex{
    
       //    int group=[self photoCount]-preadd-nextadd;
    
    NSString *indexStr = [NSString stringWithFormat:@"%d/%d",(int)_i_index,(int)_i_group];
    self.indexLabel.frame = CGRectMake(0, 0, 54.0, 42);
    self.indexLabel.center = CGPointMake(GlobleWidth/2+20.0, (GlobleHeight-67.0f/2));
    
    [self.indexLabel setText:indexStr WithFont:self.indexLabel.font AndColor:[UIColor whiteColor]];
    NSString *currentpageStr = [NSString stringWithFormat:@"%d",(int)_i_index];
    NSRange currentpageRang = [indexStr rangeOfString:currentpageStr];
    [self.indexLabel setTextdBold:currentpageRang
                         WithFont:[UIFont fontWithName:@"HelveticaNeue-Thin" size:21.0] AndColor:[UIColor whiteColor]];
}


#pragma mark - 自定义导航栏
//创建自定义导航栏
-(void)navigatorView
{
    if(self.isCover){
        __weak typeof(self) me=self;
        self.tool=[self showSliderToolbarWithType:0];
//        [self.tool handleTap:IFActive_ButtomToolBarButtonTypeDownloadImg block:^(id sender) {
//            CLPhotoViewController *ctrl= (CLPhotoViewController *)[me.slides currentChild];
//            UIImage *img=[ctrl currentImg];
//            if(img)
//                UIImageWriteToSavedPhotosAlbum(img, self,@selector(image:didFinishSavingWithError:contextInfo:), nil);
//        }];
        
    }else{
        
    
    
     self.tool=[self showSliderToolbarWithType:IFActive_ButtomToolBarButtonTypeShare|IFActive_ButtomToolBarButtonTypeCollect|
                IFActive_ButtomToolBarButtonTypeShowComment|IFActive_ButtomToolBarButtonTypeDownloadImg|IFActive_ButtomToolBarButtonTypeWriteComment];
    __weak typeof(self) me=self;
    [self.tool handleTap:IFActive_ButtomToolBarButtonTypeWriteComment block:^(id sender) {
        NSString *commentID=[me.commentDic sgrFGetStringForKey:@"topic_id"];
        if(_isStrNULL(commentID)){
            [[CLGloble sharedInstance] showTieAlertMessage:@"暂时不能评论" subMessage:@"请稍后尝试"];
            return ;
        }
        [me openComment:commentID replayId:nil block:^(NSString *cont, int select) {
            NSString *str=[NSString stringWithFormat:@"我的评论:%@ |%@ %@",_safeStr(cont),_safeStr(me.str_title),
                           _safeStr(me.shareUrl)];
            [[CLGlobleDataModel sharedInstance] shareMessage:select content:str];

        }];
    }];
    
    [self.tool handleTap:IFActive_ButtomToolBarButtonTypeShowComment block:^(id sender) {
        CTCommentViewController *commentVC = [[CTCommentViewController alloc] init];
        commentVC.isNeedRequest=NO;
        commentVC.fromtype=@"doc";
        commentVC.docTitle=me.str_title;
        commentVC.shareUrl=me.shareUrl;
        commentVC.commentTopicId=[me.commentDic sgrFGetStringForKey:@"topic_id"];
        [commentVC showCommentDic:me.commentDic];
        [[CLPushAnimatedRight sharedInstance] pushController:commentVC];

    }];
    
    [self.tool handleTap:IFActive_ButtomToolBarButtonTypeShare block:^(id sender) {
        if(_isStrNULL(me.shareUrl)){
            [[CLGloble sharedInstance] showTieSuccessMessage:@"现在不能分享" subMessage:@"缺少分享地址"];
            return ;
        }
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
//        [dic sgrSetObject:[UIImage imageNamed:@"icon114.png"] forKey:@"icon"];
        [dic sgrSetObject:[self getImageFromURL:me.sharepicUrl] forKey:@"icon"];
        
        [dic sgrSetObject:_safeStr(me.str_title) forKey:@"title"];
        [dic sgrSetObject:me.shareUrl forKey:@"url"];
        [me openShare:dic];
    }];
    
    [self.tool handleTap:IFActive_ButtomToolBarButtonTypeDownloadImg block:^(id sender) {
        CLPhotoViewController *ctrl= (CLPhotoViewController *)[me.slides currentChild];
        UIImage *img=[ctrl currentImg];
        if(img)
            UIImageWriteToSavedPhotosAlbum(img, self,@selector(image:didFinishSavingWithError:contextInfo:), nil);
    }];
    self.tool.collectId=self.itemId;
    }

}

-(UIImage *)getImageFromURL:(NSString *)fileURL {
    UIImage * result;
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    result = [UIImage imageWithData:data];
    if (result) {
        return result;
    }else
        return [UIImage imageNamed:@"icon114.png"];
}

-(void)downLoadBtPressed:(UIButton *)sender{
    CLPhotoViewController *ctrl= (CLPhotoViewController *)[self.slides currentChild];
    UIImage *img=[ctrl currentImg];
    if(img)
        UIImageWriteToSavedPhotosAlbum(img, self,@selector(image:didFinishSavingWithError:contextInfo:), nil);

}

#pragma mark - download delegate
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString * message = [error description];
    if ([message length]==0) {
        [[CLGloble sharedInstance] showTieSuccessMessage:@"提示" subMessage:@"保存成功"];
    }
    else
    {
        message = @"请开启相册访问权限";
        [[CLGloble sharedInstance] showTieAlertMessage:@"提示" subMessage:message];
    }
}

- (void)layoutSublayersOfLayer:(CALayer *)layer{
    
}

#pragma mark --Rotation--

- (void)viewWillTransitionToSize:(CGSize)size
       withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    
    if(AtLeastIOS8){
        _photointerfaceOrientation=[self device2Interface];
        if (_photointerfaceOrientation == UIInterfaceOrientationLandscapeLeft || _photointerfaceOrientation == UIInterfaceOrientationLandscapeRight) {
            __weak typeof(self) me=self;
           // self.view.frame=CGRectMake(0, 0, GlobleHeight, GlobleWidth);
           
            [UIView animateWithDuration:[coordinator transitionDuration] animations:^{
                [me.slides setFrame:CGRectMake(0, 0, GlobleHeight, GlobleWidth)];
                [me.slides updateToInterfaceOrientation:_photointerfaceOrientation];
                [me updateTitleLabelToInterfaceOrientation:_photointerfaceOrientation];
                [me updatePercentLabelToInterfaceOrientation:_photointerfaceOrientation];
                [me updateInfoLabelToInterfaceOrientation:_photointerfaceOrientation];
                [me updateButtonsToInterfaceOrientation:_photointerfaceOrientation];
                [me updateBottomViewToInterfaceOrientation:_photointerfaceOrientation];
                [me updateReTryViewToInterfaceOrientation:_photointerfaceOrientation];

            }];
            
        }
        else {
            self.view.frame=CGRectMake(0, 0, GlobleWidth, GlobleHeight);
            __weak typeof(self) me=self;
            [[SgrGCD sharedInstance] enqueueForeground:^{
                [me.slides setFrame:CGRectMake(0, 0, GlobleWidth, GlobleHeight)];
                [me.slides updateToInterfaceOrientation:_photointerfaceOrientation];
                [me updateTitleLabelToInterfaceOrientation:_photointerfaceOrientation];
                [me updatePercentLabelToInterfaceOrientation:_photointerfaceOrientation];
                [me updateInfoLabelToInterfaceOrientation:_photointerfaceOrientation];
                [me updateButtonsToInterfaceOrientation:_photointerfaceOrientation];
                [me updateBottomViewToInterfaceOrientation:_photointerfaceOrientation];
                [me updateReTryViewToInterfaceOrientation:_photointerfaceOrientation];
              }];
           
        }
    }

}

- (UIInterfaceOrientation)device2Interface{
    switch ([UIDevice currentDevice].orientation) {
        case UIDeviceOrientationPortrait:          // Device oriented vertically, home button on the bottom
            return UIInterfaceOrientationPortrait;
            break;
        case  UIDeviceOrientationPortraitUpsideDown:  // Device oriented vertically, home button on the top
            return UIInterfaceOrientationPortraitUpsideDown;
            break;
        case  UIDeviceOrientationLandscapeLeft:       // Device oriented horizontally, home button on the right
            return UIInterfaceOrientationLandscapeLeft;
            break;
        case  UIDeviceOrientationLandscapeRight:
            return UIInterfaceOrientationLandscapeRight;
            break;
            
        default:
            return UIInterfaceOrientationUnknown;
            break;
    }
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    _photointerfaceOrientation = toInterfaceOrientation;
    if(!AtLeastIOS8){
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        
        [self.slides setFrame:CGRectMake(0, 0, GlobleHeight, GlobleWidth)];
        [self.slides updateToInterfaceOrientation:toInterfaceOrientation];
        [self updateTitleLabelToInterfaceOrientation:toInterfaceOrientation];
        [self updatePercentLabelToInterfaceOrientation:toInterfaceOrientation];
        [self updateInfoLabelToInterfaceOrientation:toInterfaceOrientation];
        [self updateButtonsToInterfaceOrientation:toInterfaceOrientation];
        [self updateBottomViewToInterfaceOrientation:toInterfaceOrientation];
        [self updateReTryViewToInterfaceOrientation:toInterfaceOrientation];
    }
    else {
        [self.slides setFrame:CGRectMake(0, 0, GlobleWidth, GlobleHeight)];
        [self.slides updateToInterfaceOrientation:toInterfaceOrientation];
        [self updateTitleLabelToInterfaceOrientation:toInterfaceOrientation];
        [self updatePercentLabelToInterfaceOrientation:toInterfaceOrientation];
        [self updateInfoLabelToInterfaceOrientation:toInterfaceOrientation];
        [self updateButtonsToInterfaceOrientation:toInterfaceOrientation];
        [self updateBottomViewToInterfaceOrientation:toInterfaceOrientation];
        [self updateReTryViewToInterfaceOrientation:toInterfaceOrientation];
    }
    }
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    
}

- (void)updateBottomViewToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    //self.bottomView.backgroundColor = [UIColor clearColor];
    
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        self.slides.alpha = 1.0;
        if (_i_index == 1) {
            CGFloat heigh = [IfengPhotoLabel getHeightWithTitleLabel:self.p_titleLabel WithInfoLabel:self.p_infoLabel ToInterfaceOrientation:toInterfaceOrientation];
            [self.bottomView setFrame:CGRectMake(0, GlobleWidth-(heigh>bottomViewdefaultHeight?heigh:bottomViewdefaultHeight)-BOTTOMGAP, GlobleHeight, heigh>bottomViewdefaultHeight?heigh:bottomViewdefaultHeight)];
        }
        else
            [self.bottomView setFrame:CGRectMake(0, GlobleWidth-bottomViewdefaultHeight-BOTTOMGAP, GlobleHeight, bottomViewdefaultHeight)];
        
        [_photoBottomView setImage:[UIImage imageNamed:@"photo_bottom_horizontal.png"]];
        _photoBottomView.frame = CGRectMake(0, GlobleWidth-125.0, GlobleHeight, 125.0);
    }
    else {
        self.slides.alpha = 1.0;
        if (_i_index == 1) {
            CGFloat heigh = [IfengPhotoLabel getHeightWithTitleLabel:self.p_titleLabel WithInfoLabel:self.p_infoLabel ToInterfaceOrientation:toInterfaceOrientation];
            [self.bottomView setFrame:CGRectMake(0, GlobleHeight-(heigh>bottomViewdefaultHeight?heigh:bottomViewdefaultHeight)-BOTTOMGAP-44.0f, GlobleWidth, heigh>bottomViewdefaultHeight?heigh:bottomViewdefaultHeight)];
        }
        else
            [self.bottomView setFrame:CGRectMake(0, GlobleHeight-bottomViewdefaultHeight-BOTTOMGAP-44.0f, GlobleWidth, bottomViewdefaultHeight)];
        
        [_photoBottomView setImage:[UIImage imageNamed:@"photo_bottom_vertical.png"]];
        _photoBottomView.frame = CGRectMake(0, GlobleHeight-200.0/2-44.0f, GlobleWidth, 200.0/2);
    }
    _temp_bottomHeight = self.bottomView.frame.origin.y;
    
    //如果是最后一页，即后贴片  隐藏工具栏 和 遮罩view
    if (_i_index == _dataArray.count) {
        _photoBottomView.hidden = YES;
        self.tool.view.hidden=YES;
    }else{
        _photoBottomView.hidden=self.tool.view.hidden=self.bottomView.hidden;
    }
    
}

- (void)updateTitleLabelToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    if (_str_title && [_str_title length] >= 1) {
        [self.p_titleLabel setTitle:_str_title WithFontSize:18.0f WithGap:6.0f
                      WithTextColor:RGB(0xc1,0xc1,0xc1)];
    }
    
    if (_i_index == 1) {
        self.p_titleLabel.hidden = NO;
    }
    else
        self.p_titleLabel.hidden = YES;
    
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        self.p_titleLabel.frame = CGRectMake(50.0, 0.0f, 730.0f/2-((SCREEN_4)?0:88), 42.0f);
        if ([IfengPhotoLabel getLinesWithLabel:self.p_titleLabel] == 1) {
            self.p_titleLabel.frame = CGRectMake(50.0, 0.0f, 730.0f/2-((SCREEN_4)?0:88), 18.0f);
        }
    }
    else {
        self.p_titleLabel.frame = CGRectMake(18.0f, 0.0f, 220.0f, 42.0f);
        if ([IfengPhotoLabel getLinesWithLabel:self.p_titleLabel] == 1) {
            self.p_titleLabel.frame = CGRectMake(18.0f, 0.0f, 220.0f, 18.0f);
        }
    }
}

- (void)updatePercentLabelToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        // 算frame，以使它能够居左对齐
        self.percentLabel.frame = CGRectMake(730.0f/2-((SCREEN_4)?0:88)+70.0, _lineImageView.top+_lineImageView.bottom-25, 54.0, 42);//-4.0
        self.rightLogoImg.frame = CGRectMake(730.0f/2-((SCREEN_4)?0:88)+70.0, _lineImageView.top, 21, 44);
        
        if (_str_percent && [_str_percent length] >= 1) {
            [self.percentLabel setText:_str_percent WithFont:self.percentLabel.font AndColor:self.percentLabel.textColor];
        }
        
        NSString *currentpageStr = [NSString stringWithFormat:@"%d",(int)_i_index];
        NSRange currentpageRang = [_str_percent rangeOfString:currentpageStr];
        
        if (_str_percent && [_str_percent length] >= 1) {
            [self.percentLabel setTextdBold:currentpageRang WithFont:[UIFont fontWithName:@"HelveticaNeue-Thin" size:21.0] AndColor:self.percentLabel.textColor];
        }
    }
    else {
        // 算frame，以使它能够居左对齐
        self.percentLabel.frame = CGRectMake(266.0, _lineImageView.top+_lineImageView.bottom-25, 54.0, 42);
        self.rightLogoImg.frame = CGRectMake(266, _lineImageView.top, 21, 44);
        
        if (_str_percent && [_str_percent length] >= 1) {
            [self.percentLabel setText:_str_percent WithFont:self.percentLabel.font AndColor:self.percentLabel.textColor];
        }
        NSString *currentpageStr = [NSString stringWithFormat:@"%d",(int)_i_index];
        NSRange currentpageRang = [_str_percent rangeOfString:currentpageStr];
        if (_str_percent && [_str_percent length] >= 1) {
            [self.percentLabel setTextdBold:currentpageRang WithFont:[UIFont fontWithName:@"HelveticaNeue-Thin" size:21.0] AndColor:self.percentLabel.textColor];
        }
    }
}

- (void)updateInfoLabelToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    if (_str_info && [_str_info length] >= 1) {
        [self.p_infoLabel setTitle:_str_info WithFontSize:13.0f WithGap:6.f
                     WithTextColor:RGB(0xc1, 0xc1, 0xc1)];
    }
    else {
        _str_info = @"";
        [self.p_infoLabel setTitle:nil WithFontSize:13.0f WithGap:6.f WithTextColor:RGB(0xc1, 0xc1, 0xc1)];
    }
    
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        if (_i_index == 1) {
            self.infoScrollView.frame = CGRectMake(50.0, 10.0f+self.p_titleLabel.frame.size.height, 730.0f/2-((SCREEN_4)?0:88), GlobleHeight-50.0f-10.0f-self.p_titleLabel.frame.size.height);
        }
        else
            self.infoScrollView.frame = CGRectMake(50.0, 0.0, 730.0f/2-((SCREEN_4)?0:88), GlobleHeight-50.0f);
    }
    else {
        if (_i_index == 1) {
            self.infoScrollView.frame = CGRectMake(18.0f, 10.0f+self.p_titleLabel.frame.size.height, 220.0f, GlobleHeight-44.0f-10.0f-self.p_titleLabel.frame.size.height);
        }
        else
            self.infoScrollView.frame = CGRectMake(18.0f, 0.0, 220.0f, GlobleHeight-44.0f);
    }
    
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        
        self.p_infoLabel.frame = CGRectMake(0.0, 0.0, 730.0f/2-((SCREEN_4)?0:88), self.infoScrollView.frame.size.height);
        
        if (_i_index == 1) {
            [_lineImageView setFrame:CGRectMake(730.0f/2-((SCREEN_4)?0:88)+60.0, 0, 1, (self.p_infoLabel.frame.size.height+self.p_titleLabel.frame.size.height+10.0)>bottomViewdefaultHeight?(self.p_infoLabel.frame.size.height+self.p_titleLabel.frame.size.height+10.0):bottomViewdefaultHeight)];
        }
        else {
            if ([IfengPhotoLabel getLinesWithLabel:self.p_infoLabel]<=1) {
                [_lineImageView setFrame:CGRectMake(730.0f/2-((SCREEN_4)?0:88)+60.0, 0, 1, bottomViewdefaultHeight)];
            }
            else {
                [_lineImageView setFrame:CGRectMake(730.0f/2-((SCREEN_4)?0:88)+60.0, 0, 1, ([IfengPhotoLabel getLinesWithLabel:self.p_infoLabel]*19.0-6)>bottomViewdefaultHeight?[IfengPhotoLabel getLinesWithLabel:self.p_infoLabel]*19.0-6:bottomViewdefaultHeight)];
            }
        }
        
    }
    else {
        
        self.p_infoLabel.frame = CGRectMake(0.0, 0.0, 220.0, self.infoScrollView.frame.size.height);
        
        if (_i_index == 1) {
            [_lineImageView setFrame:CGRectMake(220.0+36.0f, 0, 1, ([IfengPhotoLabel getLinesWithLabel:self.p_infoLabel]*19.0-6+self.p_titleLabel.frame.size.height+10.0)>bottomViewdefaultHeight?([IfengPhotoLabel getLinesWithLabel:self.p_infoLabel]*19.0-6+self.p_titleLabel.frame.size.height+10.0):bottomViewdefaultHeight)];
        }
        else {
            if ([IfengPhotoLabel getLinesWithLabel:self.p_infoLabel]<=1) {
                [_lineImageView setFrame:CGRectMake(220.0+36.0f, 0, 1, bottomViewdefaultHeight)];
            }
            else {
                [_lineImageView setFrame:CGRectMake(220.0+36.0f, 0, 1, ([IfengPhotoLabel getLinesWithLabel:self.p_infoLabel]*19.0-6)>bottomViewdefaultHeight?([IfengPhotoLabel getLinesWithLabel:self.p_infoLabel]*19.0-6):bottomViewdefaultHeight)];
            }
        }
    }
}

- (void)updateButtonsToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        //横屏时 不需要 下  工具栏
        _h_backButton.hidden = YES;
        [_h_backButton setFrame:CGRectMake(0, GlobleWidth-50.f, 50.f, 50.f)];
        [_h_backButton setImage:[UIImage imageNamed:@"nav_back_photo_horizonal.png"] forState:UIControlStateNormal];
        _h_backButton.alpha = 1.0;
        _h_download.hidden = YES;
        [_h_download setFrame:CGRectMake(GlobleHeight-50.0, GlobleWidth-50, 50, 50)];
       
    }
    else {
                _h_download.hidden = YES;
        _h_backButton.hidden = YES;
        [_h_download setFrame:CGRectZero];
    }
}
                                         
                                         
- (void)updateReTryViewToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
            if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
                [self.reTry setFrame:CGRectMake(0, 0, 280, 300)];
                [self.reTry setCenter:self.slides.center];
            }
            else {
                [self.reTry setFrame:CGRectMake(0, 0, 280, 300)];
                [self.reTry setCenter:self.slides.center];
            }
}


#pragma mark --GestureRecognizer--
- (void)didSwipeBottomView:(UISwipeGestureRecognizer *)_swipeGesture
{
    [UIView animateWithDuration:0.6 animations:^{
        if (_photointerfaceOrientation == UIInterfaceOrientationLandscapeLeft || _photointerfaceOrientation == UIInterfaceOrientationLandscapeRight) {
            [self.bottomView setFrame:CGRectMake(0, _temp_bottomHeight, GlobleHeight, GlobleWidth-_temp_bottomHeight-BOTTOMGAP)];
        }
        else {
            [self.bottomView setFrame:CGRectMake(0, _temp_bottomHeight, GlobleWidth, GlobleHeight-_temp_bottomHeight-BOTTOMGAP-44.0)];
        }
        self.slides.alpha = 1.0;
    }];
}


- (void)didPanBottomView:(UIPanGestureRecognizer *)_panGesture
{
    if (!_finishMove) {
        return;
    }
    CGPoint translation = [_panGesture translationInView:self.view];
    
    switch ([_panGesture state]) {
        case UIGestureRecognizerStateBegan: {
            
        }
            break;
        case UIGestureRecognizerStateChanged: {
            
            if (self.bottomView.frame.origin.y < 24) {
                [UIView animateWithDuration:0.5 animations:^{
                    _finishMove = NO;
                    if (_photointerfaceOrientation == UIInterfaceOrientationLandscapeLeft || _photointerfaceOrientation == UIInterfaceOrientationLandscapeRight) {
                        [self.bottomView setFrame:CGRectMake(0, 24, GlobleHeight, GlobleWidth-24.0-BOTTOMGAP)];
                    }
                    else {
                        [self.bottomView setFrame:CGRectMake(0, 24, GlobleWidth, GlobleHeight-24.0-BOTTOMGAP-44.0f)];
                    }
                    
                } completion:^(BOOL finished) {
                    if (finished) {
                        _finishMove = YES;
                        _f_initial = 0;
                        [_panGesture setTranslation:CGPointMake(0, 0) inView:self.view];
                    }
                    else {
                        ;
                    }
                }];
            }
            else if (self.bottomView.frame.origin.y > _temp_bottomHeight) {
                
                [UIView animateWithDuration:0.5 animations:^{
                    _finishMove = NO;
                    if (_photointerfaceOrientation == UIInterfaceOrientationLandscapeLeft || _photointerfaceOrientation == UIInterfaceOrientationLandscapeRight) {
                        [self.bottomView setFrame:CGRectMake(0, _temp_bottomHeight, GlobleHeight, GlobleWidth-_temp_bottomHeight-BOTTOMGAP)];
                    }
                    else {
                        [self.bottomView setFrame:CGRectMake(0, _temp_bottomHeight, GlobleWidth, GlobleHeight-_temp_bottomHeight-BOTTOMGAP-44.0)];
                    }
                } completion:^(BOOL finished) {
                    if (finished) {
                        _finishMove = YES;
                        _f_initial = 0;
                        [self updateBottomViewToInterfaceOrientation:_photointerfaceOrientation];
                        [_panGesture setTranslation:CGPointMake(0, 0) inView:self.view];
                    }
                    else {
                        ;
                    }
                }];
            }
            else {
                //竖直移动底部视图
                _panGesture.view.center = CGPointMake(_panGesture.view.center.x + 0,
                                                      _panGesture.view.center.y + translation.y);
                [_panGesture setTranslation:CGPointMake(0, 0) inView:self.view];
                
                if (_photointerfaceOrientation == UIInterfaceOrientationLandscapeLeft || _photointerfaceOrientation == UIInterfaceOrientationLandscapeRight) {
                    [self.bottomView setFrame:CGRectMake(0, self.bottomView.frame.origin.y, GlobleHeight, GlobleWidth-self.bottomView.frame.origin.y-BOTTOMGAP)];
                }
                else {
                    [self.bottomView setFrame:CGRectMake(0, self.bottomView.frame.origin.y, GlobleWidth, GlobleHeight-self.bottomView.frame.origin.y-BOTTOMGAP-44.0)];
                }
                
                if (self.bottomView.frame.origin.y <= _temp_bottomHeight) {
                    double temp = fabs(self.bottomView.frame.origin.y - _temp_bottomHeight);
                    self.slides.alpha = (1-temp/44)>0.3?(1-temp/44):0.3;
                }
                else
                    self.slides.alpha = 1;
            }
        }
            break;
        case UIGestureRecognizerStateEnded: {
            ;
        }
            break;
        default:
            break;
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return YES;
}
                                        

                                         
                                         

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidDisappear:(BOOL)animated{
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    if (AtLeastIOS8){
        if([@"behind" isEqualToString:self.ref]){
            [self viewWillTransitionToSize:CGSizeZero withTransitionCoordinator:nil];
        }else {
            if(self.isCreate){
                [self viewWillTransitionToSize:CGSizeZero withTransitionCoordinator:nil];
            }else{
                self.isCreate=YES;
            }
        }
    }
    
    [self willAnimateRotationToInterfaceOrientation:self.interfaceOrientation duration:0];
}

- (void)willPop{
   // [[CLGloble sharedInstance] didChangeToInterfaceOrientationPortrait];
    [UIViewController attemptRotationToDeviceOrientation];
}

- (BOOL)__shouldAutorotate{
    if(self.willBack)return NO;
    
    if(self.isInputShow) return NO;
    return YES;
}

- (NSUInteger)__supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskAll;
}



@end
